package com.c2b.algorithm.leetcode.base;

import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://leetcode.cn/problems/word-pattern">单词规律(Word Pattern)</a>
 * <p>给定一种规律 pattern 和一个字符串 s ，判断 s 是否遵循相同的规律。</p>
 * <p>这里的 遵循 指完全匹配，例如， pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。</p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例1:
 *      输入: pattern = "abba", s = "dog cat cat dog"
 *      输出: true
 *
 * 示例 2:
 *      输入:pattern = "abba", s = "dog cat cat fish"
 *      输出: false
 *
 * 示例 3:
 *      输入: pattern = "aaaa", s = "dog cat cat dog"
 *      输出: false
 *     </pre>
 * </p>
 * <p>
 * <b>提示：</b>
 *     <ul>
 *         <li>1 <= pattern.length <= 300</li>
 *         <li>pattern 只包含小写英文字母</li>
 *         <li>1 <= s.length <= 3000</li>
 *         <li>s 只包含小写英文字母和 ' '</li>
 *         <li>s 不包含 任何前导或尾随对空格</li>
 *         <li>s 中每个单词都被 单个空格 分隔</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/10/11 13:26
 */
public class LC0290WordPattern_S {
    static class Solution {
        public boolean wordPattern(String pattern, String s) {
            String[] strings = s.split(" ");
            if (pattern.length() != strings.length) {
                return false;
            }
            Map<Character, String> characterStringHashMap = new HashMap<>();
            Map<String, Character> stringCharacterMap = new HashMap<>();
            char[] chars = pattern.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                char ch = chars[i];
                String str = strings[i];
                if (characterStringHashMap.containsKey(ch)) {
                    String mapStr = characterStringHashMap.get(ch);
                    if (!str.equals(mapStr)) {
                        return false;
                    }
                } else {
                    if (stringCharacterMap.containsKey(str)) {
                        return false;
                    }
                    characterStringHashMap.put(ch, str);
                    stringCharacterMap.put(str, ch);
                }
            }
            return true;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.wordPattern("abba", "dog cat cat dog"));
        System.out.println(solution.wordPattern("abba", "dog cat cat fish"));
        System.out.println(solution.wordPattern("aaaa", "dog cat cat dog"));
    }
}
